export default class Stage {
  canvasContainer: any
  lowerCanvas: any
  upperCanvas: any
  lowerCanvasDom: any
  upperCanvasDom: any
  ctxDom: any
  width: number = 0
  height: number = 0
  childrens: any[] = []
  constructor(domId: string) {
    this.setPageDom(domId)
    this.setDimensions({
      width: this.width,
      height: this.height,
    })
  }
  setPageDom(domId: string) {
    let content = document.getElementById(domId)!
    let container = `<div class="canvas-container" style="position: relative; user-select: none;"><canvas id="canvas" class="lower-canvas" style="position: absolute; left: 0px; top: 0px; touch-action: none; user-select: none;"></canvas><canvas class="upper-canvas" style="position: absolute; left: 0px; top: 0px; touch-action: none; user-select: none; cursor: default;"></canvas></div>`
    content.innerHTML = container
    this.ctxDom = content
    this.canvasContainer =
      this.ctxDom.getElementsByClassName('canvas-container')[0]
    this.lowerCanvasDom = this.ctxDom.getElementsByClassName('lower-canvas')[0]
    this.upperCanvasDom = this.ctxDom.getElementsByClassName('upper-canvas')[0]

    this.lowerCanvas = this.lowerCanvasDom.getContext('2d')
    this.upperCanvas = this.upperCanvasDom.getContext('2d')
  }
  // 设置画布的尺寸
  setDimensions({ width = 350, height = 350 }) {
    this.width = width
    this.height = height
    this.canvasContainer.style.width = `${this.width}px`
    this.canvasContainer.style.height = `${this.height}px`
    this.lowerCanvasDom.setAttribute('width', `${this.width}px`)
    this.lowerCanvasDom.setAttribute('height', `${this.height}px`)
    this.upperCanvasDom.setAttribute('width', `${this.width}px`)
    this.upperCanvasDom.setAttribute('height', `${this.height}px`)
  }
  add(children: any) {
    this.childrens.push(children)
  }
  async renderAll() {
    for (let k in this.childrens) {
      await this.childrens[k]._render(this.lowerCanvas)
    }

    this.upperCanvas.drawImage(
      this.lowerCanvasDom,
      0,
      0,
      this.width,
      this.height
    )
  }
}
